﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

using log4net;
using Common;
using AutoFacUtils;
using SysAdmin._02_Common;
using SysAdmin._04_Form;
using SysAdmin._04_Form._00_Common;

namespace SysAdmin
{
    static class Program
    {
        private static ILog _logger = LogManager.GetLogger(typeof(Program));

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Process instance = RunningInstance();
            if (instance == null)
            {
                _logger.Info("SysAdmin Startup...");
                CashFlow.Db.DAL.SqlSugarHelper.Init();

                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                Application.ThreadException += Application_ThreadException;
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                var form = new InitForm();
                var dr = form.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    Application.Run(new MainForm());
                }
                SysAdmin._03_Service.TimeService.Exit();
            }
            else
            {
                HandleRunningInstance(instance);
            }
        }

        private static Process RunningInstance()
        {
            Process process = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(process.ProcessName);
            foreach (Process item in processes)
            {
                if (item.Id != process.Id)
                {
                    if (item.MainModule.FileName == process.MainModule.FileName)
                    {
                        return item;
                    }
                }
            }

            return null;
        }

        private static void HandleRunningInstance(Process instance)
        {
            Win32Tool.ShowWindowAsync(instance.MainWindowHandle, 1);
            Win32Tool.SetForegroundWindow(instance.MainWindowHandle);
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            _logger.Fatal(e.Exception);
            UICommonTool.ShowAlertDialog("系统遇到未知异常，程序即将退出！");
            Application.Exit();
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            _logger.Fatal(ex);
            UICommonTool.ShowAlertDialog("系统遇到未知异常，程序即将退出！");
            Application.Exit();
        }
    }
}
